extern crate net;
use std::net::*;
use std::io::Read;
use std::io::Write;
use std::thread;

macro_rules! t
{
    ($e:expr) =>
    {
        match $e
        {
            Ok(t) => t,
            Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
        }
    }
}


fn main()
{
    let listener = t!(TcpListener::bind("0.0.0.0:9880"));

    let mut num: u8 = 0;

    println!("server is running");
    // let mut stream = t!(listener.accept()).0;
    // let mut buf = [0];

    loop
    {
        let mut stream = t!(listener.accept()).0;
        let out = stream.try_clone();
        thread::spawn(move ||
        {
            let mut buf = [0; 10];
            loop
            {
                let res = stream.read(&mut buf);
                println!("stream {:?} received: {:?}" , num, buf[0]);
                thread::sleep_ms(1000);
            }
        });
        thread::spawn(move ||
        {
            let mut out_stream = t!(out);
            loop
            {
                let res = out_stream.write(&[110]);
                thread::sleep_ms(1000);
            }
        });
        num = num + 1;
    }

}
